package com.lcredu.seckill.rabbitmq;

import com.lcredu.seckill.config.RabbitMQConfig;
import com.lcredu.seckill.config.RabbitMQConfigHeaders;
import com.lcredu.seckill.config.RabbitMQConfigTopic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 黎长容
 * @date 2025-09-05 15:02
 */
@Service
@Slf4j
public class RabbitmqSender {

    @Resource
    private RabbitTemplate rabbitTemplate;

    public void send(Object msg) {
        log.info("生产者发送了消息={}", msg);
        rabbitTemplate.convertAndSend("queue", msg);
    }

    /**
     * 取消路由机制(第二个参数为"")
     *
     * @param msg
     */
    public void sendByFanout(Object msg) {
        log.info("生产者发送了消息(fanout交换机)={}", msg);
        rabbitTemplate.convertAndSend("fanoutExchange", "", msg);
    }

    /**
     * 使用路由机制发送消息
     */
    public void sendByDirectForSuccess(Object msg) {
        log.info("direct交换机发送了成功消息={}", msg);
        rabbitTemplate.convertAndSend(RabbitMQConfig.DIRECT_EXCHANGE, RabbitMQConfig.ROUTER_KEY01, msg);
    }

    public void sendByDirectForError(Object msg) {
        log.info("direct交换机发送了失败消息={}", msg);
        rabbitTemplate.convertAndSend(RabbitMQConfig.DIRECT_EXCHANGE, RabbitMQConfig.ROUTER_KEY02, msg);
    }


    //通过topic发送消息
    //我设计这个交换机能够接受第一次的发的消息
    //第二个消息能同时被两个队列进行接受
    public void sendByTopic01(Object msg) {
        log.info("topic交换机01发出了消息={}", msg);
        rabbitTemplate.convertAndSend(RabbitMQConfigTopic.TOPIC_EXCHANGE, "queue.red.message", msg);
    }

    public void sendByTopic02(Object msg) {
        log.info("topic交换机02发出了消息={}", msg);
        rabbitTemplate.convertAndSend(RabbitMQConfigTopic.TOPIC_EXCHANGE, "com.queue.topic", msg);
    }

    //发送消息到headers交换机
    //只发给第一个消息队列
    public void sendByHeader01(String msg) {
        log.info("Header01交换机01发出了消息={}", msg);
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setHeader("name", "lcredu");
        messageProperties.setHeader("color", "yellow");
        Message message = new Message(msg.getBytes(), messageProperties);
        rabbitTemplate.convertAndSend(RabbitMQConfigHeaders.HEADER_EXCHANGE, "", message);
    }


    //两个消息队列都能接收到
    public void sendByHeader02(String msg) {
        log.info("Header01交换机02发出了消息={}", msg);
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setHeader("name", "lcredu");
        messageProperties.setHeader("color", "red");
        Message message = new Message(msg.getBytes(), messageProperties);
        rabbitTemplate.convertAndSend(RabbitMQConfigHeaders.HEADER_EXCHANGE, "", message);
    }
}
